package com.example.netty_demo.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author benjamin_5
 * @Description
 * @date 2024/8/30
 */
@Component
public class NettyClient {

    @Value("${netty.host}")
    private String host;

    @Value("${netty.port}")
    private int port;

    private EventLoopGroup group;
    private Channel channel;

    @Autowired
    private NettyClientInitializer nettyClientInitializer;

    public void start() throws InterruptedException {
        group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(nettyClientInitializer);

            channel = bootstrap.connect(host, port).sync().channel();
            System.out.println("Connected to server " + host + ":" + port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stop() {
        group.shutdownGracefully();
    }

    public boolean send(String message) throws InterruptedException {
        try{
            channel.writeAndFlush(message).sync();
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
}
